import os
from pptx import Presentation
from pptx.enum.shapes import MSO_SHAPE_TYPE
from paddleocr import PaddleOCR
from sumy.parsers.plaintext import PlaintextParser
from sumy.nlp.tokenizers import Tokenizer
from sumy.summarizers.text_rank import TextRankSummarizer
from PIL import Image

# 初始化 OCR（中文+英文）
ocr = PaddleOCR(use_angle_cls=True, lang="ch")

def extract_text_and_images(ppt_path, image_dir="ppt_images"):
    prs = Presentation(ppt_path)
    all_text = []

    if not os.path.exists(image_dir):
        os.makedirs(image_dir)

    for slide_index, slide in enumerate(prs.slides, start=1):
        # 提取文字
        for shape in slide.shapes:
            if shape.has_text_frame:
                text = shape.text.strip()
                if text:
                    all_text.append(text)

            # 提取图片
            if shape.shape_type == MSO_SHAPE_TYPE.PICTURE:
                image = shape.image
                img_bytes = image.blob
                img_path = os.path.join(image_dir, f"slide_{slide_index}.png")
                with open(img_path, "wb") as f:
                    f.write(img_bytes)

    return all_text, image_dir


def ocr_images(image_dir):
    ocr_texts = []
    for img_file in os.listdir(image_dir):
        if img_file.lower().endswith((".png", ".jpg", ".jpeg")):
            img_path = os.path.join(image_dir, img_file)
            result = ocr.ocr(img_path, cls=True)
            for line in result[0]:
                ocr_texts.append(line[1][0])
    return ocr_texts


def summarize_text(text_list, sentence_count=5):
    full_text = "\n".join(text_list)
    parser = PlaintextParser.from_string(full_text, Tokenizer("chinese"))
    summarizer = TextRankSummarizer()
    summary = summarizer(parser.document, sentence_count)
    return [str(sentence) for sentence in summary]


if __name__ == "__main__":
    ppt_file = "demo.pptx"  # 你的 PPT 文件路径

    # 1. 提取 PPT 文字 & 图片
    ppt_text, img_dir = extract_text_and_images(ppt_file)

    # 2. OCR 图片文字
    img_text = ocr_images(img_dir)

    # 3. 合并文字
    combined_texts = ppt_text + img_text

    # 4. 摘要
    summary_result = summarize_text(combined_texts, sentence_count=5)

    print("===== PPT 概括 =====")
    for sent in summary_result:
        print("-", sent)
